package com.example.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnUtils {
    //连接数据库
    public static Connection getConn(){   //Connection是连接对象   alt+enter
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");  //加载数据库的驱动类  8.0以上com.mysql.cj.jdbc.Driver5.6 com.mysql.jdbc.Driver
        conn = DriverManager.getConnection(
                "jdbc:mysql://10.47.164.186:3306/news?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false",
                "root",
                "Sa123456"
        );

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return conn;
    }

    //关闭数据库
    public static void closeConnection(Connection conn){
        try {
            conn.close();  //关闭数据库连接
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Connection conn = ConnUtils.getConn();
        if(conn !=null){
            System.out.println("连接成功");
        }else{
            System.out.println("连接失败");
        }
        //关闭连接
        ConnUtils.closeConnection(conn);
    }
}
